﻿#ifndef __YNMYSQL_H__
#define __YNMYSQL_H__

#include "YNData.h"
#include <vector>

struct MYSQL;
struct MYSQL_RES;

#ifdef YNEXPORT
#define YNAPI __declspec(dllexport)
#else
#define YNAPI __declspec(dllimport)
#endif //YNAPI

namespace YN {

	class YNAPI YNMysql
	{
	public:
		//初始化Mysql API
		bool Init();

		//清理占用的所有资源
		void Close();

		//数据库连接（不考虑线程安全） flag设置支持多条语句
		bool Connect(const char*host, const char*user, const char*pass, const char*db, unsigned short port = 3306, unsigned long flag = 0);

		//执行sql语句  if sqllen=0 strlen获取字符长度
		bool Query(const char*sql, unsigned long sqllen = 0);

		//Mysql参数的设定 Connect之前调用
		bool Options(YN_OPT opt, const void *arg);

		//连接超时时间
		bool SetConnectTimeout(int sec);

		//自动重连，默认不自动
		bool SetReconnect(bool isre = true);

		//结果集获取
		//返回全部结果
		bool StoreResult();

		//开始接收结果，通过Fetch获取
		bool UseResult();

		//释放结果集占用的空间
		void FreeResult();

		//获取一行数据
		std::vector<YNData> FetchRow();

		//生成insert sql语句
		std::string GetInsertSql(XDATA &kv, std::string table);

		//插入非二进制数据
		bool Insert(XDATA &kv, std::string table);

		//插入二进制数据
		bool InsertBin(XDATA kv, std::string table);

		//获取更新数据的sql语句 where语句中，用户要包含where
		std::string GetUpdateSql(XDATA &kv, std::string table, std::string where);
		//返回更新数量，失败返回-1
		int Update(XDATA &kv, std::string table, std::string where);
		int UpdateBin(XDATA &kv, std::string table, std::string where);

		//事务接口
		bool StartTransaction();
		bool StopTransaction();
		bool Commit();
		bool Rollback();

		//简易接口,返回select的数据结果，每次调用清理上一次的结果集
		XROWS GetResult(const char *sql);
	protected:
		MYSQL *mysql = NULL;
		MYSQL_RES *result = NULL;
	};

}

#endif //__YNMYSQL_H__
